<?php


namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;

class BaseModel extends Model {
    protected $primaryKey = "id"; //主键
    public $incrementing = true;  //主键是否自增
    public $timestamps = true;    //自动管理时间戳
    protected $dateFormat = "U";  //时间样式
    protected $scopeLimit = true;//数据查询范围,设置为true时,数据查询将自动增加site_id条件
    protected $declares = []; //
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];



    public function registerGlobalScopes($builder) {
            //自定义模型自动添加内置条件,可以通过 Model::withoutGlobalScope('site_id_scope')形式去除
            if ($this->scopeLimit && Schema::hasColumn($this->table, 'site_id') && getCurrentSiteId()) {
                static::addGlobalScope('site_id_scope', function (Builder $builder) {
                    $siteId = getCurrentSiteId();
                    $builder->where($this->table.'.site_id', '=', $siteId);
                });
            }

        foreach ($this->getGlobalScopes() as $identifier => $scope) {
            $builder->withGlobalScope($identifier, $scope);
        }
        return $builder;
    }

    /**
     * 判断模型中是否存在某字段
     * @param string $column
     * @return bool
     */
    public function hasColumn($column) {
        return Schema::hasColumn($this->table, $column);
    }

    /**
     * 统一条件传入
     * @param array|null $condition
     * @return mixed
     */
    public function whereBuilder(array $condition=null) {
        $where=[];
        if($condition) {
            foreach ($condition as $k => $v) {
                if (in_array($k, array_keys($this->declares))) {
                    $where[]=array_merge($this->declares[$k], [$v]);
                }
            }
        }
        return $this->where($where);
    }

    /**
     * 更新过滤无效字段
     */
    public function getUpdateData(){
        return $this->fillable;
    }
}
